/* 
 * Binary Tree InOrder Traversal
 */

#include "../../func.h"

vector<int> inorderTraversal(TreeNode *root)
{
    vector<int> result;
    stack<TreeNode *> s;
    TreeNode *p = root;
    while (!s.empty() || p != nullptr) {
        if (p != nullptr) {
            s.push(p);
            p = p->left;
        } else {
            p = s.top();
            s.pop();
            result.push_back(p->val);
            p = p->right;
        }
    }
    return result;
}

//morris
vector<int> morris(TreeNode *root) {
    vector<int> result;
    TreeNode *cur = root, *prev = nullptr;

    while (cur != nullptr) {
        if (cur->left == nullptr) {
            result.push_back(cur->val);
            prev = cur;
            cur = cur->right;
        }
        else
        {
            TreeNode *node = cur->left;
            while (node->right != nullptr && node->right != cur) {
                node = node->right;
            }

            if (node->right == nullptr) {
                node->right = cur;
                cur = cur->left;
            }
            else {
                result.push_back(cur->val);
                node->right = nullptr;
                prev = cur;
                cur = cur->right;
            }
        }       
    }
    return result;
}